<template>
  <div>
    <el-dialog v-drag width="45%" :title="!dataForm.supplierId ? '新增供应商' : '修改供应商'" :close-on-click-modal="false"
      @close="handleCloseSupplierDialog" :visible.sync="visible">
      <el-form :model="dataForm" :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
        label-width="150px">
        <el-tabs v-model="activeName" @tab-click="handleClick" type="card">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="类型" prop="supllierType">
              <el-select size="mini" @focus="getDicts('SUPPLY_TYPE')" v-model="dataForm.supllierType" clearable
                placeholder="请选择">
                <el-option v-for="item in supllierTypes" :key="item.value" :label="item.label" :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="supplierName">
              <el-input size="mini" v-model="dataForm.supplierName" placeholder="供应商名称"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input size="mini" v-model="dataForm.address" placeholder="地址"></el-input>
            </el-form-item>
            <el-form-item label="销售人员" prop="salesman">
              <el-input size="mini" v-model="dataForm.salesman" placeholder="销售人员"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="tel">
              <el-input size="mini" v-model="dataForm.tel" placeholder="电话"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input size="mini" v-model="dataForm.mobile" placeholder="手机"></el-input>
            </el-form-item>
            <el-form-item label="法人代表" prop="corporater">
              <el-input size="mini" v-model="dataForm.corporater" placeholder="法人代表"></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="leader">
              <el-input size="mini" v-model="dataForm.leader" placeholder="负责人"></el-input>
            </el-form-item>
            <el-form-item label="组织机构代码" prop="organizationCode">
              <el-input size="mini" v-model="dataForm.organizationCode" placeholder="组织机构代码"></el-input>
            </el-form-item>
            <el-form-item label="组织机构期限" prop="organizationTimeLimit">
              <el-date-picker v-model="dataForm.organizationTimeLimit" align="right" type="date" placeholder="选择日期"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="税务号" prop="taxNumber">
              <el-input size="mini" v-model="dataForm.taxNumber" placeholder="税务号"></el-input>
            </el-form-item>
            <el-form-item label="营业执照期限" prop="businessTimeLimit">
              <el-date-picker v-model="dataForm.businessTimeLimit" align="right" type="date" placeholder="选择日期"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="产品经营许可证期限" prop="productTimeLimit">
              <el-date-picker v-model="dataForm.productTimeLimit" align="right" type="date" placeholder="选择日期"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="证件上传" name="image" :inline="false">
            <el-form-item label="营业执照" prop="licenses" :inline="false">
              <el-upload :action="uploadUrl" :on-preview="handleLicensePreview" :on-remove="handleLicenseRemove"
                :on-success="handLicenseSuccess" :before-upload="handleLicenseBeforeUpload" :headers="headers"
                :file-list="dataForm.licenses" :drag="false" list-type="picture" name="file" :data="uploadData">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>

            <br />
            <el-form-item label="产品经营许可证" prop="productCerts" :inline="false">
              <el-upload :action="uploadUrl" :on-preview="handleProductCertPreview" :on-remove="handleProductCertRemove"
                :on-success="handProductCertSuccess" :before-upload="handleProductCertBeforeUpload" :headers="headers"
                :file-list="dataForm.productCerts" :drag="false" list-type="picture" name="file" :data="uploadData">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>

          </el-tab-pane>

          <el-tab-pane label="供应商描述" name="remark">
            <el-form-item label="供应商描述" prop="remark">
              <quill-editor ref="remark" v-model="dataForm.remark" class="editor" :options="editorOption" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-drag title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <el-image style="width: 100%;" @close="handCloseImgDialog" :src="previewPath"></el-image>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getFileName
  } from '@/utils/myUtil.js'
  export default {
    data() {
      return {
        visible: false,
        dataForm: {
          supplierId: null,
          supllierType: '',
          supplierName: '',
          address: '',
          salesman: '',
          tel: '',
          mobile: '',
          corporater: '',
          businessLicense: '',
          businessTimeLimit: '',
          productBusinessLlicense: '',
          productTimeLimit: '',
          leader: '',
          organizationCode: '',
          organizationTimeLimit: '',
          taxNumber: '',
          remark: '',
          licenses: [],
          productCerts: []
        },
        dataRule: {
          supllierType: [{
            required: true,
            message: '供应商类型不能为空',
            trigger: 'blur'
          }],
          supplierName: [{
            required: true,
            message: '供应商名称不能为空',
            trigger: 'blur'
          }],
          address: [{
            required: true,
            message: '地址不能为空',
            trigger: 'blur'
          }],
          salesman: [{
            required: true,
            message: '销售人员不能为空',
            trigger: 'blur'
          }],
          tel: [{
            required: true,
            message: '电话不能为空',
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '手机不能为空',
            trigger: 'blur'
          }],
          corporater: [{
            required: true,
            message: '法人代表不能为空',
            trigger: 'blur'
          }],
          licenses: [{
            required: true,
            message: '营业执照不能为空',
            trigger: 'blur'
          }],
          businessTimeLimit: [{
            required: true,
            message: '营业执照期限不能为空',
            trigger: 'blur'
          }],
          productCerts: [{
            required: true,
            message: '产品经营许可证不能为空',
            trigger: 'blur'
          }],
          productTimeLimit: [{
            required: true,
            message: '产品经营许可证期限不能为空',
            trigger: 'blur'
          }],
          leader: [{
            required: true,
            message: '负责人不能为空',
            trigger: 'blur'
          }],
          organizationCode: [{
            required: true,
            message: '组织机构代码不能为空',
            trigger: 'blur'
          }],
          organizationTimeLimit: [{
            required: true,
            message: '组织机构期限不能为空',
            trigger: 'blur'
          }],
          taxNumber: [{
            required: true,
            message: '税务号不能为空',
            trigger: 'blur'
          }],
        },
        supllierTypes: [],
        editorOption: {
          placeholder: '请输入......'
        },
        previewPath: '',
        imgDialogVisible: false,
        uploadUrl: 'http://localhost:99/api/common/upload',
        headers: {
          Authorization: "Bearer " + this.$cookie.get('token'),
          token: this.$cookie.get('token')
        },
        uploadData: {
          file: ''
        },
        license: {},
        productCert: {},
        activeName: 'basic',
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
      }
    },
    methods: {
      init(id) {
        this.dataForm.supplierId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.supplierId) {
            this.$http({
              url: this.$http.adornUrl(`/goods/goodssupplier/info/${this.dataForm.supplierId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {

                let licenses = []
                if (data.goodsSupplier.businessLicense) {
                  let urls = data.goodsSupplier.businessLicense.split(",")
                  urls.forEach(url => {
                    let license = {
                      "name": getFileName(url),
                      "url": url
                    }
                    licenses.push(license)
                  })
                }

                let productCerts = []
                if (data.goodsSupplier.productBusinessLlicense) {
                  let urls = data.goodsSupplier.productBusinessLlicense.split(",")
                  urls.forEach(url => {
                    let productCert = {
                      "name": getFileName(url),
                      "url": url
                    }
                    productCerts.push(productCert)
                  })
                }
                this.dataForm = data.goodsSupplier
                this.dataForm.licenses = licenses
                this.dataForm.productCerts = productCerts

              }
            })
          }
        })
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if (type === 'SUPPLY_TYPE') {
            this.supllierTypes = data.data
          }
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {

            if (this.dataForm.licenses.length > 0) {
              let urls = []
              this.dataForm.licenses.forEach(item => {
                urls.push(item.url)
              })
              this.dataForm.businessLicense = urls.join(",")
            }else{
				this.dataForm.businessLicense = ''
			}

            if (this.dataForm.productCerts.length > 0) {
              let urls = []
              this.dataForm.productCerts.forEach(item => {
                urls.push(item.url)
              })
              this.dataForm.productBusinessLlicense = urls.join(",")
            }else{
				this.dataForm.productBusinessLlicense = ''
			}

            this.$http({
              url: `/goods/goodssupplier/${!this.dataForm.supplierId ? 'save' : 'update'}`,
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      //----营业执照-----------------------------
      handleLicensePreview(file, fileList) {
        this.previewPath = file.url
        this.imgDialogVisible = true
      },
      //图片删除
      handleLicenseRemove(file) {
        //找到索引
        const index = this.dataForm.licenses.findIndex(item =>
          item.url === file.url
        )
        //根据索引删除
        this.dataForm.licenses.splice(index, 1)
      },
      //上传之前
      handleLicenseBeforeUpload(file) {
        this.license = {
          "name": file.name,
          "size": file.size,
          "type": file.type,
          "uid": file.uid,
          "status": 1,
        }
      },
      //上传成功
      handLicenseSuccess(response) {
        if (response.code === 0) {
          this.license.url = response.data
          this.dataForm.licenses.push(this.license)
        }
      },
      //--产品经营许可证-----------------------------------
      handleProductCertPreview(file, fileList) {
        this.previewPath = file.url
        this.imgDialogVisible = true
      },
      //图片删除
      handleProductCertRemove(file) {
        //找到索引
        const index = this.dataForm.productCerts.findIndex(item =>
          item.url === file.url
        )
        //根据索引删除
        this.dataForm.productCerts.splice(index, 1)
      },
      //上传之前
      handleProductCertBeforeUpload(file) {
        this.productCert = {
          "name": file.name,
          "size": file.size,
          "type": file.type,
          "uid": file.uid,
          "status": 1,
        }
      },
      //上传成功
      handProductCertSuccess(response) {
        if (response.code === 0) {
          this.productCert.url = response.data
          this.dataForm.productCerts.push(this.productCert)
        }
      },
      handCloseImgDialog() {
        this.previewPath = ''
      },
      handleClick() {

      },
      handleCloseSupplierDialog() {
        this.dataForm = {}
        this.productCert = {}
        this.license = {}
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-form--inline .el-form-item__label {
    width: 150px !important;
  }
</style>
